﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Windvoice.Library
{
    public static class HttpHelper
    {
        /// <summary>
        /// Post data到url
        /// </summary>
        /// <param name="data">要post的数据</param>
        /// <param name="url">目标url</param>
        /// <returns>服务器响应</returns>
        public static string SendPost(string data, string url)
        {
            byte[] bytesToPost = Encoding.UTF8.GetBytes(data);

            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest httpRequest = webRequest as HttpWebRequest;

            httpRequest.Method = "POST";

            httpRequest.ContentLength = data.Length;
            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(bytesToPost, 0, data.Length);
            requestStream.Close();

            Stream responseStream = httpRequest.GetResponse().GetResponseStream();

            string stringResponse = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();

            return stringResponse;
        }

        public static string SendGet(string url)
        {
            WebRequest webRequest = WebRequest.Create(url);
            HttpWebRequest httpRequest = webRequest as HttpWebRequest;

            httpRequest.Method = "GET";

            Stream responseStream = httpRequest.GetResponse().GetResponseStream();

            string stringResponse = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();

            return stringResponse;
        }
    }
}
